package com.ledim.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import com.crashlytics.android.Crashlytics;
import com.facebook.drawee.view.SimpleDraweeView;
import com.ledim.activity.base.LeDimBaseActivity;
import com.ledim.bean.LaunchImageUrlBean;
import com.ledim.bean.LedimPushBean;
import com.ledim.bean.base.BaseResultDataInfo;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.FrescoUtil;
import com.ledim.utils.LedimBitmapUtils;
import com.ledim.utils.LedimFunctionUtils;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LogUtil;
import com.letv.android.young.client.R;
import io.fabric.sdk.android.Fabric;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.ledim.utils.ConstantUtil.LAUNCH_IMAGE_NAME;
import static com.ledim.utils.ConstantUtil.LAUNCH_IMAGE_PATH;

/**
 * 闪屏页
 */
public class SplashActivity extends LeDimBaseActivity {

    private SimpleDraweeView mLaunchImage;
    private Handler mHandler = new Handler();
    private LedimPushBean mPushBean;

    @Override
    protected int getContentLayoutId() {
        return R.layout.splash;
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPushBean = (LedimPushBean) getIntent().getSerializableExtra(ConstantUtil.DATA);
        if (MainActivity.getInstance() == null) {
            Fabric.with(this, new Crashlytics());
            mLaunchImage = findViewByIdExt(R.id.sdv_lanuch_image);
            if (!TextUtils.isEmpty(LedimSpUtils.getLaunchImageUrl()) &&
                    !TextUtils.isEmpty(getLocalLaunchImagePath())) {
                //本地有图片
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showLaunchImage();
                    }
                }, 1000);
                delay2TargetActivity(2000);
            } else {
                delay2TargetActivity(1000);
            }
        } else {
            delay2TargetActivity(0);
        }
        getLaunchImageUrl();
    }

    /**
     * 下载图片
     *
     * @param url
     */
    private void downLoadLaunchImage(final String url) {
        if (url.endsWith("gif")) {
            FrescoUtil.downloadGif(url, this, new FrescoUtil.BitmapListener() {
                @Override
                public void onSuccess(Bitmap bitmap, InputStream is) {
                    try {
                        saveGifImage(LAUNCH_IMAGE_PATH, LAUNCH_IMAGE_NAME, is);
                        LedimSpUtils.setLaunchImageUrl(url);

                    } catch (Exception e) {
                        e.printStackTrace();
                        deleteLocalLaunchImage();
                    }
                }

                @Override
                public void onFail() {

                }
            });
        } else {
            FrescoUtil.getBitmap(url, this, 0, 0, new FrescoUtil.BitmapListener() {
                @Override
                public void onSuccess(Bitmap bitmap, InputStream is) {
                    if (bitmap != null) {
                        //保存到本地
                        try {
                            LedimBitmapUtils.saveBitmap2Storage(LAUNCH_IMAGE_PATH, LAUNCH_IMAGE_NAME, bitmap);
                            //设置url,保存到本地
                            LedimSpUtils.setLaunchImageUrl(url);
                        } catch (Exception e) {
                            e.printStackTrace();
                            deleteLocalLaunchImage();
                        }
                    }
                }

                @Override
                public void onFail() {

                }
            });
        }
    }

    /**
     * 获取广告图片url
     */
    private void getLaunchImageUrl() {
        LedimApiServiceFactory.createService(ApiService.class)
                              .getLaunchImageUrl()
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseResultDataInfo<LaunchImageUrlBean>>() {
                                  @Override
                                  public void onError(Throwable e) {
                                      super.onError(e);
                                      LogUtil.e(e.getMessage());
                                  }

                                  @Override
                                  public void onCompleted() {
                                      super.onCompleted();
                                  }

                                  @Override
                                  public void onNext(
                                          BaseResultDataInfo<LaunchImageUrlBean> dataInfo) {
                                      super.onNext(dataInfo);
                                      if (dataInfo.success && dataInfo.data != null) {
                                          String url = dataInfo.data.ANDROID;
                                          if (!TextUtils.isEmpty(url)) {
                                              //获取图片名字
                                              LAUNCH_IMAGE_NAME = "splash" +
                                                      url.substring(url.length() - 4, url.length());
                                              if (dataInfo.data.ANDROID.equals(LedimSpUtils.getLaunchImageUrl())) {
                                                  //本地url和网上url一致，但是本地没有图片
                                                  if (TextUtils.isEmpty(getLocalLaunchImagePath())) {
                                                      downLoadLaunchImage(dataInfo.data.ANDROID);
                                                  }

                                              } else {
                                                  //不一致
                                                  deleteLocalLaunchImage();
                                                  downLoadLaunchImage(dataInfo.data.ANDROID);
                                              }
                                          }
                                      }
                                  }
                              });

    }

    /**
     * 删除本地图片
     */
    private void deleteLocalLaunchImage() {
        String localLaunchImagePath = getLocalLaunchImagePath();
        if (!TextUtils.isEmpty(localLaunchImagePath)) {
            File localFile = new File(localLaunchImagePath);
            if (localFile.exists()) {
                localFile.delete();
            }
        }
    }

    /**
     * 获取本地图片地址
     *
     * @return
     */
    private String getLocalLaunchImagePath() {
        File lanuchImageFile = new File(LAUNCH_IMAGE_PATH);
        File[] files = lanuchImageFile.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.getName().contains("splash")) {
                    return file.getAbsolutePath();
                }
            }
        }
        return null;
    }

    /**
     * 延迟进到相应页面
     */
    private void delay2TargetActivity(int time) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mPushBean == null) {
                    goToOthersF(MainActivity.class);
                } else {
                    Intent intent =
                            LedimFunctionUtils.getPushMsgIntent(mPushBean, SplashActivity.this);
                    intent.putExtra(ConstantUtil.FROM_PUSH_MSG, true);
                    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    if (intent == null) {
                        goToOthersF(MainActivity.class);
                    } else {
                        startActivity(intent);
                        finish();
                    }
                }
            }
        }, time);
    }

    /**
     * 显示启动图片
     */
    private void showLaunchImage() {
        String url = LedimSpUtils.getLaunchImageUrl();
        String imageName = "splash" + url.substring(url.length() - 4, url.length());
        FrescoUtil.loadUrl("file://" + LAUNCH_IMAGE_PATH + imageName, mLaunchImage);
    }

    /**
     * 将InputStream转成gif并保存本地
     *
     * @param path
     * @param imageName
     * @param ins
     */
    private void saveGifImage(String path, String imageName, InputStream ins) throws Exception {

        File appDir = new File(path);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }

        File file = new File(appDir, imageName);
        FileOutputStream fos = new FileOutputStream(file);

        byte[] b = new byte[1024 * 4];
        int nRead = 0;
        while ((nRead = ins.read(b)) != -1) {
            fos.write(b, 0, nRead);
        }
        fos.flush();
        fos.close();
        ins.close();
    }
}
